package main

import (
	"context"
	"encoding/gob"
	"encoding/json"
	"gitee.com/MrDaiM/goodscenter/model"
	"gitee.com/MrDaiM/msgo"
	"gitee.com/MrDaiM/msgo/register"
	"gitee.com/MrDaiM/msgo/rpc"
	"gitee.com/MrDaiM/msgo/tracer"
	"gitee.com/MrDaiM/ordercenter/service"
	"github.com/opentracing/opentracing-go"
	"github.com/opentracing/opentracing-go/ext"
	"github.com/uber/jaeger-client-go"
	"github.com/uber/jaeger-client-go/config"
	"log"
	"net/http"
	"time"
)

func main() {
	engine := msgo.Default()

	client := rpc.NewHttpClient()

	group := engine.Group("order")

	goodsService := &service.GoodsService{}
	client.Use("goodsService", goodsService)

	createTracer, closer, err := tracer.CreateTracer("orderCenter",
		&config.SamplerConfig{
			Type:  jaeger.SamplerTypeConst,
			Param: 1,
		},
		&config.ReporterConfig{
			LogSpans:          true,
			CollectorEndpoint: "http://192.168.152.136:14268/api/traces",
		}, config.Logger(jaeger.StdLogger),
	)
	if err != nil {
		log.Println(err)
	}
	defer closer.Close()

	group.Get("/find", func(ctx *msgo.Context) {
		// 通过商品中心，查询商品的信息
		// http的方式进行调用
		val := ctx.GetQuery("id")
		params := make(map[string]any)
		params["id"] = val
		params["name"] = 1000

		span := createTracer.StartSpan("find")
		defer span.Finish()
		session := client.Session()
		session.ReqHandler = func(req *http.Request) {
			//
			ext.SpanKindRPCClient.Set(span)
			createTracer.Inject(span.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header))
		}
		body, err := session.Do("goodsService", "Find").(*service.GoodsService).Find(params)
		if err != nil {
			panic(err)
		}
		result := model.Result{}
		_ = json.Unmarshal(body, &result)

		_ = ctx.JSON(http.StatusOK, result)
	})

	//group.Get("/findGrpc", func(ctx *msgo.Context) {
	//	conn, err := grpc.Dial("127.0.0.1:9111", grpc.WithTransportCredentials(insecure.NewCredentials()))
	//	if err != nil {
	//		fmt.Println(err)
	//	}
	//	defer conn.Close()
	//
	//	apiClient := api.NewGoodsApiClient(conn)
	//	rsp, err := apiClient.Find(context.TODO(), &api.GoodsRequest{})
	//	if err != nil {
	//		fmt.Println(err)
	//	}
	//	_ = ctx.JSON(http.StatusOK, rsp)
	//})

	//group.Get("/findGrpc", func(ctx *msgo.Context) {
	//	config := rpc.DefaultGrpcClientConfig()
	//	config.Address = "127.0.0.1:9111"
	//	client, _ := rpc.NewGrpcClient(config)
	//
	//	defer client.Conn.Close()
	//
	//	apiClient := api.NewGoodsApiClient(client.Conn)
	//	rsp, err := apiClient.Find(context.TODO(), &api.GoodsRequest{})
	//	if err != nil {
	//		fmt.Println(err)
	//	}
	//	_ = ctx.JSON(http.StatusOK, rsp)
	//})

	//rpc.DefultOption.SerializeType = rpc.ProtoBuff
	//proxy := rpc.NewMsTcpClientProxy(rpc.DefultOption)

	//group.Get("/findTcp", func(ctx *msgo.Context) {
	//
	//	// // gob序列化和反序列化  同一目录的对象是不需要进行注册的，不同服务间传递的相同对象，使用前需要进行注册
	//	gob.Register(&model.Result{})
	//	gob.Register(&model.Goods{})
	//
	//	args := make([]any, 1)
	//	args[0] = int64(10)
	//	result, err := proxy.Call(context.Background(), "goods", "Find", args)
	//	if err != nil {
	//		panic(err)
	//	}
	//	_ = ctx.JSON(http.StatusOK, result)
	//})

	option := rpc.DefultOption
	option.SerializeType = rpc.ProtoBuff
	option.RegisterType = "etcd"
	option.RegisterOption = register.Option{
		Endpoints:   []string{"127.0.0.1:2379"},
		DialTimeout: 5 * time.Second,
		//Host:        "127.0.0.1",
		//Port:        9222,
	}

	proxy := rpc.NewMsTcpClientProxy(option)
	group.Get("/findTcp", func(ctx *msgo.Context) {

		// // gob序列化和反序列化  同一目录的对象是不需要进行注册的，不同服务间传递的相同对象，使用前需要进行注册
		gob.Register(&model.Result{})
		gob.Register(&model.Goods{})

		args := make([]any, 1)
		args[0] = int64(10)

		result, err := proxy.Call(context.Background(), "goods", "Find", args)
		if err != nil {
			panic(err)
		}
		_ = ctx.JSON(http.StatusOK, result)
	})

	engine.Run(":9003")
}

//
//func example() {
//	engine := msgo.Default()
//
//	client := rpc.NewHttpClient()
//
//	group := engine.Group("order")
//	group.Get("/find", func(ctx *msgo.Context) {
//		// 通过商品中心，查询商品的信息
//		// http的方式进行调用
//		params := make(map[string]any)
//		params["id"] = 1000
//		params["name"] = 1000
//		bytes, err := client.PostJson("http://localhost:9002/goods/find", params)
//		if err != nil {
//			ctx.Logger.Error(err)
//		}
//		fmt.Println(string(bytes))
//		v := &model.Result{}
//		_ = json.Unmarshal(bytes, v)
//		_ = ctx.JSON(http.StatusOK, v)
//	})
//
//}
